package com.quarkus.exception;

import lombok.extern.slf4j.Slf4j;
import org.jboss.resteasy.reactive.server.ServerExceptionMapper;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.stream.Collectors;

/**
 * @version v1.0
 * @Description: Rest service  全局异常处理
 * @Author: TongRui乀
 * @Date: 2021/1/24 2:46 下午
 *
 *  返回值只支持 Response 或者 Uni<Response>
 */
@Slf4j
public class GlobalExceptionHandler {

    @ServerExceptionMapper
    public Response globalExceptionHandler(Exception e){
        log.error("global exception ", e);
        return Response.status(500).entity("SYSTEM ERROR").build();
    }

    @ServerExceptionMapper(ConstraintViolationException.class)
    public Response ConstraintViolationExceptionHandler(ConstraintViolationException e){

        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(","));

        log.error("param validate error {}", message);

        HashMap<String, Object> result = new HashMap<>();

        result.put("code", 400);
        result.put("msg", "参数校验失败");
        result.put("data", message);

        return Response.status(400).entity(result).build();
    }

}
